package com.woniuxy.thred.syn;

/**
 * description: Happ12306 <br>
 * date: 2022/2/6 3:44 上午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */
//快乐火车
public class Happ12306 {
    public static void main(String[] args) {
        Web12306 c = new Web12306(4, "蜗牛影院");
        new Passenger(c, "zs", 2).start();
        new Passenger(c, "ls", 1).start();
    }
}

//顾客
class Passenger extends Thread {
    //位置
    int seats;

    public Passenger(Runnable target, String name, int seats) {
        super(target, name);
        this.seats = seats;
    }
}

//火车票网
class Web12306 implements Runnable {
    //可用位置
    int available;
    //名称
    String name;

    public Web12306(int available, String name) {
        this.available = available;
        this.name = name;
    }

    @Override
    public void run() {
        Passenger p = (Passenger) Thread.currentThread();
        boolean flag = this.bookTickets(p.seats);
        if (flag) {
            System.out.println("出票成功" + Thread.currentThread().getName() + "-<位置为：" + p.seats);
        } else {
            System.out.println("出票失败" + Thread.currentThread().getName() + "-<位置不够！");
        }
    }

    //购票
    public synchronized boolean bookTickets(int seats) {
        System.out.println("可用位置：" + available);
        if (seats > available) {
            return false;
        }
        available -= seats;
        return true;
    }
}